//
//  MyLikeViewController.m
//  Project_B
//
//  Created by 黑黑 on 15/11/29.
//  Copyright © 2015年 Atom_Wang. All rights reserved.
//

#import "MyLikeViewController.h"
#import "GXProviderDetailTableViewCell.h"
#import "WCG_O_Detail_DetailProviderViewController.h"
#import "GXSuggestArticelTableViewCell.h"
#import "GXSuggestImageViewTableViewCell.h"
#import "WCG_O_DetailItemViewController.h"
@interface MyLikeViewController ()<UITableViewDataSource, UITableViewDelegate, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource>

@property (nonatomic, retain) NSMutableArray *dataArr;

@end

@implementation MyLikeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.title = @"我的收藏";
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBarHidden = NO;
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self createTableViewWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.emptyDataSetSource = self;
    self.tableView.emptyDataSetDelegate = self;
    [self.tableView registerClass:[GXProviderDetailTableViewCell class] forCellReuseIdentifier:@"procell"];
    [self.tableView registerClass:[GXSuggestArticelTableViewCell class] forCellReuseIdentifier:@"ArticleCell"];
    [self.tableView registerClass:[GXSuggestImageViewTableViewCell class] forCellReuseIdentifier:@"ImageCell"];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:self action:@selector(left)];
    [UIView animateWithDuration:1.5 animations:^{
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectZero];
        [self.view addSubview:button];
        [button setBackgroundImage:[UIImage imageNamed:@"bottom_btn_back_active"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(backToFront) forControlEvents:UIControlEventTouchUpInside];
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.view).with.offset(15);
            make.bottom.mas_equalTo(self.view).with.offset(-15);
            make.width.mas_equalTo(35);
            make.height.mas_equalTo(35);
        }];
    }];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    UIView *temp = self.tabBarController.view.subviews[2];
    [UIView animateWithDuration:1 animations:^{
        self.navigationController.navigationBar.translucent = NO;
        self.automaticallyAdjustsScrollViewInsets = NO;
        self.navigationController.navigationBarHidden = NO;
        temp.frame = CGRectMake(0, kScreenHeight, kScreenWidth, 49);
    }];
    self.dataArr = [NSMutableArray array];
    [self getData];
}

- (void)backToFront
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)getData
{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"SpecialModel" inManagedObjectContext:self.manager.managedObjectContext];
    [fetchRequest setEntity:entity];
#if 1
    // Specify criteria for filtering which objects to fetch
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"type = %@", @"prolike"];
    [fetchRequest setPredicate:predicate];
    // Specify how the fetched objects should be sorted
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"title"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
#endif
    NSError *error = nil;
    NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"空");
    }
    for (SpecialModel *spe in fetchedObjects) {
        [self.dataArr addObject:spe];
    }
    // 搜索suggestModel
    NSEntityDescription *entitySug = [NSEntityDescription entityForName:@"SuggestModel" inManagedObjectContext:self.manager.managedObjectContext];
    [fetchRequest setEntity:entitySug];
    // Specify criteria for filtering which objects to fetch
    NSPredicate *predicateSug = [NSPredicate predicateWithFormat:@"today = %@", @0];
    [fetchRequest setPredicate:predicateSug];
    // Specify how the fetched objects should be sorted
    NSSortDescriptor *sortDescriptorSug = [[NSSortDescriptor alloc] initWithKey:@"title"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptorSug, nil]];
    
    NSError *errorsug = nil;
    NSArray *fetchedObjectsSug = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&errorsug];
    if (fetchedObjectsSug == nil) {
        NSLog(@"空");
    }
    for (SuggestModel *sug in fetchedObjectsSug) {
        [self.dataArr addObject:sug];
    }
    [self.tableView reloadData];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GXSuggestArticelTableViewCell *articleCell = [tableView dequeueReusableCellWithIdentifier:@"ArticleCell"];
    
    GXSuggestImageViewTableViewCell *imageViewCell = [tableView dequeueReusableCellWithIdentifier:@"ImageCell"];
    
    GXProviderDetailTableViewCell *specialCell = [tableView dequeueReusableCellWithIdentifier:@"procell"];
    id temp = self.dataArr[indexPath.row];
    if ([temp isKindOfClass:[SuggestModel class]]) {
        SuggestModel *suggestModel = (SuggestModel *)temp;
        //九宫格 大型画册 视频
        if (suggestModel.type.integerValue == 1 || suggestModel.type.integerValue == 2 || suggestModel.type.integerValue == 9) {
            articleCell.coreSugModel = self.dataArr[indexPath.row];
            return articleCell;
        }
        //文章
        else if (suggestModel.type.integerValue == 0) {
            //推荐文章
            if (suggestModel.is_recommended.integerValue) {
                articleCell.coreSugModel = self.dataArr[indexPath.row];
                return articleCell;
            }
            //不推荐文章
            else {
                specialCell.coreSugModel = self.dataArr[indexPath.row];
                return specialCell;
            }
        }
        else {
            imageViewCell.coreSugModel = self.dataArr[indexPath.row];
            return imageViewCell;
        }
    }else
    {
        GXProviderDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"procell"];
        [cell.detailImageView sd_setImageWithURL:[NSURL URLWithString:[self.dataArr[indexPath.row] title_font]]];
        cell.titleLabel.text = [self.dataArr[indexPath.row] title];
        cell.specialLabel.text = @"";
        cell.nameLabel.text = [self.dataArr[indexPath.row] content_update_time];
        return cell;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    id temp = self.dataArr[indexPath.row];
    if ([temp isKindOfClass:[SuggestModel class]]) {
        WCG_O_DetailItemViewController *item = [[WCG_O_DetailItemViewController alloc] init];
        item.url = [self.dataArr[indexPath.row] item_url];
        item.titleStr = [self.dataArr[indexPath.row] title];
        [self.navigationController pushViewController:item animated:YES];
    }else{
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        WCG_O_Detail_DetailProviderViewController *detailVC = [[WCG_O_Detail_DetailProviderViewController alloc] init];
        detailVC.link = [self.dataArr[indexPath.row] share_text];
        detailVC.title = [self.dataArr[indexPath.row] title];
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    id temp = self.dataArr[indexPath.row];
    if ([temp isKindOfClass:[SuggestModel class]]) {
        SuggestModel *suggestModel = (SuggestModel *)temp;
        //文本宽度
        CGFloat titleW = self.tableView.frame.size.width - 25 - [UIImage imageNamed:@"icon-image-album"].size.width;
        //标题文本高度
        CGRect titleSize = [suggestModel.title SizeWithTextFontSize:kSuggestTitleFontSize textWidth:titleW];
        //副标题文本高度
        CGRect subTitleSize = [suggestModel.type_name SizeWithTextFontSize:KSuggestIntroFontSize textWidth:titleW];
        
        //音乐/大型画册/九宫格
        if (suggestModel.type.integerValue == 10 || suggestModel.type.integerValue == 9 || suggestModel.type.integerValue == 1 || suggestModel.type.integerValue == 2) {
            //返回行高
            return  330 + titleSize.size.height + subTitleSize.size.height + 0.1;
        }
        //文章
        else if (suggestModel.type.integerValue == 0) {
            //推荐文章与不推荐文章返回高度
            return suggestModel.is_recommended.integerValue == 0 ? 160 : 330 + titleSize.size.height + subTitleSize.size.height + 0.1;
        }
        //诗歌
        else {
            return 350;
        }
    }else
{
    return 110;
}

}

#pragma mark - 当数据为空时显示的图片
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
{
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    return [UIImage imageNamed:@"icon-search-article"];
}

#pragma mark - 当数据为空时显示的字符
-(NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
{
    NSString *text = @"还没有收藏文章哦~";
    NSDictionary *str = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:16.0f]};
    return [[NSAttributedString alloc] initWithString:text attributes:str];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = YES;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
